/*
 * Copyright © 2021 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springboot.mbp.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.PackageConfig;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义生成文件存储路径处理器。
 *
 * @author Denvie
 * @date 2021/12/18
 * @since 1.0.0
 */
public class PathInfoHandler {
    private final Map<OutputFile, String> pathInfo = new HashMap<>();

    public PathInfoHandler(String outputDir, String xmlOutputDir, PackageConfig packageConfig) {
        pathInfo.put(OutputFile.entity,
                joinPath(outputDir, packageConfig.getPackageInfo(ConstVal.ENTITY)));
        pathInfo.put(OutputFile.mapper,
                joinPath(outputDir, packageConfig.getPackageInfo(ConstVal.MAPPER)));
        pathInfo.put(OutputFile.mapperXml, xmlOutputDir);
        pathInfo.put(OutputFile.service,
                joinPath(outputDir, packageConfig.getPackageInfo(ConstVal.SERVICE)));
        pathInfo.put(OutputFile.serviceImpl,
                joinPath(outputDir, packageConfig.getPackageInfo(ConstVal.SERVICE_IMPL)));
        pathInfo.put(OutputFile.controller,
                joinPath(outputDir, packageConfig.getPackageInfo(ConstVal.CONTROLLER)));
    }

    /**
     * 获取存储路径信息。
     */
    public Map<OutputFile, String> getPathInfo() {
        return Collections.unmodifiableMap(this.pathInfo);
    }

    /**
     * 连接路径字符串。
     *
     * @param parentDir   路径常量字符串
     * @param packageName 包名
     * @return 连接后的路径
     */
    private String joinPath(String parentDir, String packageName) {
        if (StringUtils.isBlank(parentDir)) {
            parentDir = System.getProperty(ConstVal.JAVA_TMPDIR);
        }
        if (!StringUtils.endsWith(parentDir, File.separator)) {
            parentDir += File.separator;
        }
        packageName = packageName.replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
        return parentDir + packageName;
    }
}
